package com.aurora.CETManagementSystem.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean() {
        //第一步 先从ShiroFilterFactoryBean 获取实例
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager());

        shiroFilterFactoryBean.setLoginUrl("/index");

        shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized");//设置未认证 跳转的页面


        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();


         //<!-- authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问-->

        filterChainDefinitionMap.put("/index", "anon"); //首页授权
        filterChainDefinitionMap.put("/login", "anon"); //登录授权
        filterChainDefinitionMap.put("/register", "anon"); //注册授权
        filterChainDefinitionMap.put("/user/**", "anon"); //登录注册操作授权
        filterChainDefinitionMap.put("/student/schoolCounts", "anon"); //数据统计接口在管理员身份下不生效问题。
        filterChainDefinitionMap.put("/i18n/**", "anon"); //国际化操作授权
        filterChainDefinitionMap.put("/asserts/**", "anon");//静态资源授权
        filterChainDefinitionMap.put("/student/**", "perms[student]");
        filterChainDefinitionMap.put("/admin/**", "perms[admin]");

        //这行代码必须放在所有权限设置的最后，不然会导致所有 url 都被拦截 剩余的都需要认证
        filterChainDefinitionMap.put("/**", "authc");

        //给shiroFilterFactoryBean设置自定义的拦截规则.
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

        return shiroFilterFactoryBean;

    }

    @Bean
    public DefaultWebSecurityManager securityManager() {
        DefaultWebSecurityManager defaultSecurityManager = new DefaultWebSecurityManager();

        //这个SecurityManager里面需要set一个Realm对象
        defaultSecurityManager.setRealm(permissionRealm());

        return defaultSecurityManager;
    }

    @Bean
    public PermissionRealm permissionRealm() {
        PermissionRealm permissionRealm = new PermissionRealm();
        return permissionRealm;
    }

    @Bean
    //整合ShiroDialect:用来整合 Shiro thymeleaf
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}
